package com.adxon.servlet;

import com.adxon.MsgException;
import com.adxon.cookie.Badge;
import com.adxon.cookie.Station;
import com.adxon.data.User;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class SigninServlet extends ServletBase{
	public void doGet(HttpServletRequest req,HttpServletResponse resp)
			throws IOException,ServletException{
		Station s=Station.get(req);
		if(s==null){
			if(req.getParameter("setcookie")==null){
				s=new Station();
				s.addTo(resp);
				resp.sendRedirect(req.getRequestURI()+"?setcookie");
			}else forward("cookie.jsp",req,resp);
			return;
		}
		User u=new User();
		u.setAccount(req.getParameter("account"));
		u.setPassword(req.getParameter("password"));
		String j=req.getParameter("go");
		if(req.getParameter("ok")!=null){
			try{
				u.update();
				u.checkPassword();
				s.setOwner(u);
				s.addTo(resp);
				Badge b=new Badge();
				b.setOwner(u);
				b.addTo(resp);
				if(j==null)
					resp.sendRedirect("/");
				else{
					resp.setContentType("text/plain");
					print(resp,"200 OK");
				}
				return;
			}catch (MsgException e){
				e.getMessage(req);
			}
		}
		if(j==null){
			setAttributes(req,"Sign in");
			req.setAttribute("Account",u.getAccount());
			req.setAttribute("Password",u.getPassword());
			forward("signin.jsp",req,resp);
		}else{
			resp.setContentType("text/plain");
			print(resp,"400 Bad Request");
		}
	}
	public void doPost(HttpServletRequest req,HttpServletResponse resp)
			throws IOException,ServletException{
		doGet(req,resp);
	}
}